<?php

namespace Admin\Controller;

use Common\Logic\UserLogic;

class UserController extends CommonController
{
    /**
     *  任务添加
     */
    public function create_task()
    {
        $mobile = I('mobile');
        $data = M('admin', '', 'KEFU')->where(['status' => 1, 'role_id' => 2])->field('id,name')->order('agent_status asc,role_id asc')->select();
        $this->assign(array(
            'data' => $data,
            'mobile' => $mobile
        ));
        $this->display();
    }

    /**
     *  任务列表
     */
    public function task_list()
    {
        $page = I('page', 1);
        $num = 3;
        $first = ($page - 1) * $num;
        $where = [];
        $where['accept'] = $_SESSION['id'];
        $data = M('task', '', 'KEFU')->where($where)->field('id,title,task_time,status')->limit($first, $num)->order('status asc,ctime desc')->select();
        $time = time();

        foreach ($data as $k => $v) {
            $day = floor(abs(($time - $v['task_time']) )/ (24 * 3600));//天数
            $data[$k]['day'] = $day;
            $hour_time = abs(($time - $v['task_time']))- $day * (24 * 3600);//小时时间戳
            $hour = floor($hour_time / 3600);
            $data[$k]['hour'] = $hour;
            $data[$k]['task_time'] = date('Y-m-d H:i', $v['task_time']);

            //判断是否超时
            if ($v['task_time'] < time()) {
                $data[$k]['over_date'] = 1;//超时
            } else {
                $data[$k]['over_date'] = 2;//未超时
            }
        }
        if (empty($data)) {
            $this->ajaxReturn(['code' => '1002', 'result' => '']);
            die;
        }
        $this->ajaxReturn(['code' => '1001', 'result' => $data]);
    }

    /**
     * 添加任务
     */
    public function addTask()
    {
        $title = I('title');
        $task_time = I('task_time');
        $remark = I('remark');
        $recive = I('accept');
        $mobile = I('mobile');
        $task_time = strtotime($task_time);
        if ($recive == '0') {
            $recive = $_SESSION['id'];
        }

        $vid = M('user', '', 'USER')->where(['mobile' => $mobile])->getfield('vid');
        $arr = array('title' => $title, 'task_time' => $task_time, 'vid' => $vid, 'ctime' => time(), 'remark' => $remark, 'publish' => $_SESSION['id'], 'accept' => $recive);
        $add = M('task', '', 'KEFU')->add($arr);

        if ($add) {
            add_log('添加用户任务' . $add);
            $this->ajaxReturn(['code' => '1001', 'result' => '添加成功']);
        } else {
            $this->ajaxReturn(['code' => '1002', 'result' => '添加失败']);
        }
    }

    /**
     *  获取任务指定客服
     */
    public function getKf()
    {
        $data = M('admin', '', 'KEFU')->where(['status' => 1])->field('id,name,status,agent_status')->limit(10)->order('agent_status asc , role_id asc')->select();
        $this->ajaxReturn(['code' => '1001', 'result' => $data]);
    }

    /**
     *  任务
     */
    public function task()
    {
        $task_id = I('task_id');
        $time = time();
        if (empty($task_id)) {
            //默认展示最新的任务
            $where = [];
            $where['accept'] = $_SESSION['id'];
            $data = M('task', '', 'KEFU')->where($where)->field('title,task_time,id,remark,status')->limit(1)->order('status asc,id desc')->find();
            if (empty($data)) {
                echo '当前无任务!';
                die;
            }
        } else {
            $where = [];
            $where['id'] = $task_id;
            $data = M('task', '', 'KEFU')->where($where)->field('title,task_time,id,remark,status')->find();
        }

        //任务日期
        $day =floor( abs(($time - $data['task_time'])) / (24 * 3600));//天数
        $data['day'] = $day;
        $hour_time = abs(($time - $data['task_time'])) - $day * (24 * 3600);//小时时间戳
        $hour = floor($hour_time / 3600);

        $data['hour'] = $hour;
        //判断是否超时
        if ($data['task_time'] < time()) {
            $data['over_date'] = 1;//超时
        } else {
            $data['over_date'] = 2;//未超时
        }

        if ($data['status'] == 1) {
            $data['status_s'] = '未执行';
        }

        if ($data['status'] == 2) {
            $data['status_s'] = '已执行';
        }
        $data['task_time'] = date('Y-m-d H:i', $data['task_time']);
        //当前任务的历史回复
        $where = [];
        $where['f_id'] = $data['id'];
        $field = 'a.content,a.ctime,b.name,b.id';
        $feedback = M('task_feedback', '', 'KEFU')->join('a join admin b on a.admin_id=b.id')->where($where)->field($field)->order('a.ctime desc')->select();
        foreach ($feedback as $k => $v) {
            $feedback[$k]['ctime'] = date('Y-m-d H:i', $v['ctime']);
        }

        $this->assign(array(
            'data' => $data,
            'task_id' => $data['id'],
            'feedback' => $feedback
        ));

        $this->display();
    }
    /**
     *  任务备注提交
     */
    public function task_pull()
    {
        $task_id = I('task_id');
        $content = I('content');
        $arr = array('f_id' => $task_id, 'admin_id' => $_SESSION['id'], 'content' => $content, 'ctime' => time());
        $add = M('task_feedback', '', 'KEFU')->add($arr);
        if ($add) {
            M('task', '', 'KEFU')->where(['id'=>$task_id])->setfield('status', 2);
            add_log('任务备注'.$add);
            $this->ajaxReturn(['code' => '1001', 'result' => '备注成功！']);
        } else {
            $this->ajaxReturn(['code' => '1002', 'result' => '备注失败！']);
        }
    }

    /**
     *  任务备注列表
     */
    public function task_feedback()
    {
        $task_id = I('task_id');
        //当前任务的历史回复
        $where = [];
        $where['f_id'] = $task_id;
        $field = 'a.content,a.ctime,b.name,b.id';
        $feedback = M('task_feedback', '', 'KEFU')->join('a join admin b on a.admin_id=b.id')->where($where)->field($field)->order('a.ctime desc')->select();
        foreach ($feedback as $k => $v) {
            $feedback[$k]['ctime'] = date('Y-m-d H:i', $v['ctime']);
        }
        $this->ajaxReturn(['code' => '1001', 'result' => $feedback]);
    }

    /**
     *  任务备注列表
     */
    public function user_center()
    {
        $this->display();
    }
    /**
     * 优惠券派送
     */
    public function coupon_view()
    {
        $phone = I('phone');
        $this->assign(array('phone'=>$phone));
        $this->display();
    }


    /**
     * 优惠券派送 客服只派送亲亲券  面值20  id 7
     * 客服经理可以随意派送
     */
    public function coupon_send()
    {
        $phone = I('phone');
        $money = I('money');
        $vid = M('user', '', 'USER')->where(['mobile' => $phone])->getField('vid');

        $post_data = array(
            'money' => $money,
            'vid' => $vid,
        );

        $ret = $this->send_post(OutParamController::$compensate_coupon, $post_data);
        $json = json_decode($ret);
        add_log('优惠券派送'.$vid);
        $this->ajax($json->code, $json->result);

        //http://adm.jyyjrfw.com/External/external_give_compensate_coupon
//        //优惠券是否能发放
//        $status = M('coupon', '', 'CAIWU')->where(['id' => '7'])->getfield('status');
//        if ($status == '2') {
//            $this->ajax('1002', '无优惠券可送！');
//            die;
//        }
//
//        //是否送过
//        $exit = M('user_coupon', '', 'CAIWU')->where(['vid' => $vid, 'coupon_id' => '7'])->find();
//        if (!empty($exit)) {
//            $this->ajax('1002', '该用户已经送过亲亲券！');
//            die;
//        }
//        $arr = array('vid' => $vid, 'coupon_id' => '7', 'status' => '1', 'money' => '20', 'ctime' => time(), 'endtime' => time() * 70 * 365 * 24 * 3600);
//        if (M('user_coupon', '', 'CAIWU')->add($arr)) {
//            //用户手机
//
//            add_log('派送亲亲券'.$vid);
//            $phone = M('user', '', 'USER')->where(['vid' => $vid])->getfield('mobile');
//            send_sms($phone, '很抱歉给您造成不便！作为补偿，20元现金优惠券已放入您的账户【共享现金】');
//            $this->ajax('1001', '赠送成功');
//            die;
//        }
//        $this->ajax('1001', '赠送失败');
        die;

    }
    /**
     * 人工扣款
     */
    public function Debit()
    {
        $phone = I('phone');
        $vid = M('user', '', 'USER')->where(['mobile' => $phone])->getField('vid');
        $post_data = array(
            'vid' => $vid,
        );

        $user = M('debit_record', '', 'KEFU')->where(['vid' => $vid])->find();
        if (empty($user)) {
            add_log('人工扣款'.$phone);
            $data = array('vid' => $vid, 'updtime' => date('Y-m-d', time()), 'kefu_name' => $_SESSION['name']);
            M('debit_record', '', 'KEFU')->add($data);
            $ret = $this->send_post(OutParamController::$auto_repay, $post_data);
            $json = json_decode($ret);
            $this->ajax($json->code, $json->result);
        } else {
            $now = date('Y-m-d', time());
            if ($user['updtime'] == $now) {
                $this->ajax('1002', '一天只能调用一次');
            } else {
                M('debit_record', '', 'KEFU')->where(['vid' => $vid])->setfield('updtime', date('Y-m-d', time()));
                $ret = $this->send_post(OutParamController::$auto_repay, $post_data);
                $json = json_decode($ret);
                $this->ajax($json->code, $json->result);
            }
        }
    }

    //预约借款 弹框界面
    public function user_debt()
    {
        $vid = I('get.id');
        $field = 'id,days,money,ctime,play_time,status';
        $data = M('user_appointment', '', 'CAIWU')->where(['vid' => $vid])->field($field)->order('ctime desc')->limit(0, 10)->select();
        foreach ($data as $k => $v) {
            $data[$k]['ctime'] = date('Y-m-d H:i', $v['ctime']);
            $data[$k]['status_s'] = $v['status'];
            if ($v['status'] == 1) {
                $data[$k]['status'] = '待打款';
            } else if ($v['status'] == 2) {
                $data[$k]['status'] = '打款成功';
            } else if ($v['status'] == 3) {
                $data[$k]['status'] = '打款失败';
            } else if ($v['status'] == 4) {
                $data[$k]['status'] = '已取消';
            } else if ($v['status'] == 5) {
                $data[$k]['status'] = '打款中';
            }
        }
        $this->assign(array(
            'data' => $data
        ));
        $this->display();
    }

    //修改用户信息视图
    public function edit_user_info()
    {

        $vid = I('vid');
        $logic=new  UserLogic();
        $data=$logic->getUserInfo();
        $this->assign(array(
            'user' => $data['user'],
            'user_pic' => $data['user_pic'],
            'vid' => $vid
        ));
        $this->display();
    }


    //用户信息修改 保存
    public function user_save()
    {
         $logic=new UserLogic();
         $ret=$logic->setUserSave();
         $this->ajax($ret['code'],$ret['msg'],$ret['data']);

    }

    /**
     *减免罚息
     */
    public function reduce_fine()
    {
        $vid = I('get.vid');
        $repayment_no = I('get.repayment_no');
        $overdue_no = I('get.overdue_no');
        if (empty($_POST)) {
            $this->assign(array(
                'vid' => $vid,
                'repayment_no' => $repayment_no,
                'overdue_no' => $overdue_no
            ));
            $this->display();
            die;
        }
        $reduce_money = I('money');
        $reason = I('reason');
        $repayment_no = I('repayment_no');
        $overdue_no = I('overdue_no');

        //重复申请
        $apply = M('fine_modify_apply', '', 'URGE')->where(['repayment_no' => $repayment_no])->find();
        if (!empty($apply)) {
            $this->ajax('1002', '不可重复申请');
            die;
        }

        //判断申请金额有没有超过罚金
        $repay_money = M('overdue_order', '', 'CAIWU')->where(['overdue_no' => $overdue_no])->getfield('repay_money');
        if ($repay_money < $reduce_money) {
            $this->ajax('1002', '申请金额大于罚金');
            die;
        }
        $post_data = array(
            'repayment_no' => $repayment_no,
            'reduce_money' => $reduce_money,
            'reason' => $reason,
            'merchant_num' => 'dh_kefu',
            'urge_admin' => $_SESSION['name'],
        );
        add_log('申请减免罚息');
        $ret = $this->send_post('http://adm.jyyjrfw.com/External/external_apply_modify_fine', $post_data);
        $json = json_decode($ret);
        $this->ajax($json->code, $json->result);
    }

    /**
     *可申请减免罚息 逾期订单
     */
    public function overdue_list()
    {
        $vid = I('get.vid');
        $data = M('overdue_order', '', 'CAIWU')->where(['vid' => $vid, 'status' => '1'])->field('repay_money,repayment_no,overdue_no,repay_time')->order('id desc')->limit(1)->select();
        //是否存在已经申请
        if (!empty($data)) {
            foreach ($data as $k => $v) {
                $data[$k]['repay_time'] = date('Y-m-d H:i:s', $v['repay_time']);
                $apply = M('fine_modify_apply', '', 'URGE')->where(['repayment_no' => $data[$k]['repayment_no']])->field('status')->find();
                if (empty($apply)) {
                    $data[$k]['check_status'] = '1';//没有申请过
                } else {
                    $data[$k]['check_status'] = '2';//申请过
                    switch ($apply['status']) {
                        case 1:
                            $data[$k]['check_result'] = '待审核';
                            break;
                        case 2:
                            $data[$k]['check_result'] = '审核通过';
                            break;
                        case 3:
                            $data[$k]['check_result'] = '驳回';
                            break;
                        case 4:
                            $data[$k]['check_result'] = '已修改';
                            break;
                    }
                }
            }
        }

        $this->assign(array(
            'data' => $data,
            'vid' => $vid
        ));
        $this->display();
        die;
    }

    /**
     * 人工取消预约
     */
    public function cancel_apt()
    {
        $id = I('id');
        $post_data = array(
            'id' => $id
        );
        add_log('取消用户预约');
        $ret = $this->send_post(OutParamController::$cancel_bespeak, $post_data);
        $json = json_decode($ret);
        $this->ajax($json->code, $json->result);
    }

    //base64图片转换 并上传
    function change_base64_img()
    {
        $face_base = I('face_base');
        $type = I('type');
        $vid = I('vid');
        $path = 'Public/';
        $new_file = $this->base64_to_image($face_base, $path);
        $image['name'] = $new_file;
        $url = 'http://gxxj.oss-cn-hangzhou.aliyuncs.com';
        $success = new \Service\OssClient('LTAI6sZcsEa0SGHc', '053o9lXKyeLh1J1nmlykMg0z8N0Q5E', $url);
        $ext = strtolower(trim(substr($image['name'], strrpos($image['name'], '.')), '.'));
        $image['name'] = md5(time() . uniqid());
        $object = 'adm/' . $image['name'] . '.' . $ext;
        $filePath = $image['tmp_name'];
        try {
            $success->uploadFile('gxxj', $object, $new_file);
            $res = $url . '/adm/' . $image['name'] . '.' . $ext;
        } catch (Exception $e) {
            printf(__FUNCTION__ . ": FAILED\n");
            printf($e->getMessage() . "\n");
            $res = '1003';
        }

        if ($res == '1002') {
            $data['result'] = '图片不得大于2M';
        } else {
            $data['result'] = $res;
        }
        unlink($new_file);
        if ($type == '1') {//正面
            //修改数据
            $update = M('user_idcard_img', '', 'USER')->where(['vid' => $vid])->setfield('front', $res);
        }
        if ($type == '2') {//反面
            //修改数据
            $update = M('user_idcard_img', '', 'USER')->where(['vid' => $vid])->setfield('behind', $res);
        }
        if ($update) {
            echo json_encode(array('code' => '1001', 'result' => 'success', 'data' => $res));
            die;
        } else {
            echo json_encode(array('code' => '1001', 'result' => 'failed', 'data' => $res));
            die;
        }

    }

    public function base64_to_image($base64, $path)
    {

        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64, $result)) {
            $type = $result[2];
            $new_file = $path . time() . ".{$type}";
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64)))) {
                return $new_file;
            } else {
                return false;
            }
        }

    }

    /**
     *申请恢复额度
     */
    public function user_apply_quota()
    {
        $vid = I('vid');
        if (empty($_POST)) {
            $data = M('applyfor_recheck', '', 'KEFU_FK')->where(['vid' => $vid])->field('examine_name,examine_time,examine_status,ctime,reson,content,name')->select();
            foreach ($data as $k => $v) {
                if ($v['examine_status'] == 1) {
                    $data[$k]['examine_status'] = '待审核';
                } else if ($v['examine_status'] == 2) {
                    $data[$k]['examine_status'] = '审核通过';
                } else if ($v['examine_status'] == 3) {
                    $data[$k]['examine_status'] = '驳回';
                }
                if (!empty($v['examine_time'])) {
                    $data[$k]['examine_time'] = date('Y-m-d H:i', $v['examine_time']);
                } else {
                    $data[$k]['examine_time'] = "--";
                }
                $data[$k]['ctime'] = date('Y-m-d H:i', $v['ctime']);
            }
            $this->assign(array(
                'vid' => $vid,
                'data' => $data,
            ));
            $this->display();
            die;
        }
        $content = I('content');
        $reason = I('reason');
        //重复申请
        $info = M('applyfor_recheck', '', 'KEFU_FK')->where(['vid' => $vid, 'examine_status' => '1'])->find();
        if (!empty($info)) {
            $this->ajax('1002', '不可重复申请');
        }
        $arr = array('vid' => $vid, 'ctime' => time(), 'reson' => $reason, 'content' => $content, 'name' => $_SESSION['name']);
        $add = M('applyfor_recheck', '', 'KEFU_FK')->add($arr);
        if ($add) {
            $data = M('applyfor_recheck', '', 'KEFU_FK')->where(['vid' => $vid])->field('examine_name,examine_time,examine_status,ctime,reson,content,name')->select();
            foreach ($data as $k => $v) {
                if ($v['examine_status'] == 1) {
                    $data[$k]['examine_status'] = '待审核';
                } else if ($v['examine_status'] == 2) {
                    $data[$k]['examine_status'] = '审核通过';
                } else if ($v['examine_status'] == 3) {
                    $data[$k]['examine_status'] = '驳回';
                }
                if (!empty($v['examine_time'])) {
                    $data[$k]['examine_time'] = date('Y-m-d H:i', $v['examine_time']);
                } else {
                    $data[$k]['examine_time'] = "--";
                }
                $data[$k]['ctime'] = date('Y-m-d H:i', $v['ctime']);
            }
            echo $this->ajaxReturn(['code' => '1001', 'result' => 'success', 'data' => $data]);
        } else {
            $this->ajax('1002', '申请失败');
        }
    }

    /**
     * 申请重新认证
     */
    public function application_again()
    {
        $phone = I('phone');
        $vid = M('user', '', 'USER')->where(['mobile' => $phone])->getField('vid');
        $post_data = array(
            'vid' => $vid
        );
        add_log('申请重新认证'.$vid);
        $ret = $this->send_post('https://yapi.56gxxj.com/Kefu/kf_check_agin', $post_data);
        $json = json_decode($ret);
        $this->ajax($json->ret, $json->code);

    }

    /**
     * 催促审核
     */
    public function urge_pass()
    {
        $phone = I('phone');
        $vid = M('user', '', 'USER')->where(['mobile' => $phone])->getField('vid');
        $status = M('anti_check_user', '', 'KEFU')->where(['vid' => $vid])->field('status,urge_status')->find();
        if ($status['status'] == '2') {
            if ($status['urge_status'] == '2') {//已经催促
                $this->ajax('1002', '催促中');
                die;
            }
            $arr=array('urge_status'=>2,'urge_time'=>time());
            $update = M('anti_check_user', '', 'KEFU')->where(['vid' => $vid])->save($arr);
            if ($update)
            {
                add_log('催促审核'.$vid);
                $this->ajax('1001', '催促成功');
            }
            die;
        } else {
            $this->ajax('1002', '不符合催促条件');// 可能是用户不属于反欺诈 or 用户不是待接收状态
            die;
        }

    }

    /**
     * 发送短信
     */
    public function send_msg()
    {
        $this->display();
    }

    /**
     * 获取短信模板
     */
    public function get_msg()
    {
        $n=I('page');
        $num=5;
        $page=($n-1)*$num;
        $count=M('user_short_message','','KEFU')->where(['status'=>1])->count();
        $data=M('user_short_message','','KEFU')->where(['status'=>1])->limit($page,$num)->field('id,content')->select();
        $count=intval($count);
        $tol=ceil($count/$num);
        $this->ajaxReturn(array('code'=>'1001','result'=>$data,'tol'=>$tol,'count'=>$count));
    }

    /**
     * 获取短信模板
     */
    public function message_send()
    {
        $phone=I('phone');
        $id=I('id');
        $content=M('user_short_message','','KEFU')->where(['id'=>$id])->getField('content');
        $result=send_sms($phone, $content);
        add_log('给用户'.$phone.'发送短信'.$content);
        $this->ajaxReturn(array('code'=>'1001','data'=>$result,'content'=>$content,''));
    }

    /**
     * 通话记录页面
     */
    public function add_tel_record(){

        $phone=I('phone');
        $callid=I('callid');

        if(empty($callid)){
            echo '没有通话可以创建';
            die;
        }

//        $user=M('user','','USER')->where(['mobile'=>$phone])->field('id,truename,mobile,vid')->find();
//        if(empty($user)){
            $user['truename']  ='非平台用户';
            $user['mobile']  =$phone;
            $user['vid']  ='1';
//        }else{
//            $user['mobile']  =$user['id'];
//        }

        $content= M('call_info','','KEFU')->where(['callid'=>$callid])->field('id,content')->find();
        if(!empty($content)){
            $user['content']=$content['content'];
        }else{
            $user['content']="";
        }

        $this->assign(array(
            'user'=>$user,
            'callid'=>$callid,
        ));
        $this->display();
    }

    /**
     * 添加来电内容
     */
    public function add_call(){
        $phone=I('phone');
        $callid=I('callid');
        $content=I('content');
        $commit_type=I('commit_type');
        $commit_status=I('commit_status');
        $reply_time=I('reply_time');
        $type=I('back_type');
        $vid=I('vid');
        $category=I('category');
        if(empty($reply_time) || $reply_time==""){
            $reply_time='';
        }else{
            $reply_time=strtotime($reply_time);
        }
//        $arr=array('content'=>$content, 'back_time'=>$reply_time,'feedback_time'=>time(),'category'=>1 );
        $arr=array('content'=>$content,'back_type'=>$type,'back_time'=>$reply_time,'feedback_time'=>time() ,'category'=>$category,'communicate_type'=>$commit_type);

        $add=M('call_info','','KEFU')->where(['callsheetid'=>$callid])->save($arr);

        if($add){
//            if($type=='2'){
//                $arr1=array('title'=>'给用户'.$phone.'回电','vid'=>$vid,'task_time'=>$reply_time,'remark'=>$content,'ctime'=>time(),'publish'=>$_SESSION['id'],'accept'=>$_SESSION['id']);
//                M('task','','KEFU')->add($arr1);
//            }
            //抢拨未认证
//            $arr=array('admin'=>$_SESSION['name'],'dial_status'=>2,'has_over'=>$commit_status);
//            $action_id=M('call_info','','KEFU')->where(['callsheetid'=>$callid])->getfield('actionid');
//            M('kf_snatch','','KEFU')->where(['call_id'=>$action_id])->save($arr);
//            add_log('添加来电内容');
            $this->ajaxReturn(array('code'=>'1001','result'=>'提交成功'));
        }else{
            $this->ajaxReturn(array('code'=>'1002','result'=>'提交失败'));
        }
    }

        /**
     * 发送post请求
     * @param string $url 请求地址
     * @param array $post_data post键值对数据
     * @return string
     */
    public function send_post($url, $post_data)
    {
        $postdata = http_build_query($post_data);
        $options = array(
                'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => $postdata,
                'timeout' => 15 * 60 // 超时时间（单位:s）
            )
        );

        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
    }

}